//Modded

package com.ece400.abrc;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import de.Mjpeg.MjpegView;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class ABRC extends Activity{
	
	Button btn_connection_robot;
	Button btn_connection_cameras;
	Button btn_settings;
	Button btn_debug_x_y;

	//called when we get to the main menu (either 1st start of app, or we quit and resumed app)
	@Override
	public void onCreate(Bundle savedInstanceState){
		
		int i;
		MjpegView cam_view;
		DefaultHttpClient httpclient;	
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		PreferenceManager.setDefaultValues(this, R.layout.preferences, false);
		
		//get button objects
		btn_connection_cameras = (Button)findViewById(R.id.btn_connection_cameras);
		btn_connection_robot = (Button)findViewById(R.id.btn_connection_robot);
		btn_settings = (Button)findViewById(R.id.btn_settings);
		MjpegView.btn_cams_back = (Button)findViewById(R.id.btn_cams_back);
		//btn_debug_x_y = (Button)findViewById(R.id.btn_debug_x_y);
		
		//set button event listeners
		btn_connection_robot.setOnClickListener(connectionListenerRobot);
		btn_connection_cameras.setOnClickListener(connectionListenerCameras);
		btn_settings.setOnClickListener(settingsListener);
		//btn_debug_x_y.setOnClickListener(debugListener);
		
		//Get the video feed objects
		for(i=0;i<MjpegView.NumCameras;i++){
			
			switch(i){
			case 0:
				cam_view = (MjpegView) findViewById(R.id.mjpegView0);
				break;
			case 1:
				cam_view = (MjpegView) findViewById(R.id.mjpegView1);
				break;
			case 2:
				cam_view = (MjpegView) findViewById(R.id.mjpegView2);
				break;
				default:
					cam_view = null;
					break;
			}
			MjpegView.HttpClients[i] = new DefaultHttpClient();
	        HttpParams http_params = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(http_params, 10000);
			MjpegView.HttpClients[i].setParams(http_params);
			cam_view.setOnClickListener(MjpegView.streamClickListener);
			MjpegView.Mvs[i] = cam_view;
			cam_view.Id = i;
		}
	}
	
	/*
	Used to access the robot PWM debugging screen
	private OnClickListener debugListener = new OnClickListener() {
		public void onClick(View v) {
			Intent debugActivity = new Intent(getBaseContext(),Debug.class);
			startActivity(debugActivity);
		}
	};
	*/
		
	private OnClickListener settingsListener = new OnClickListener() {
		public void onClick(View v) {
			Intent settingsActivity = new Intent(getBaseContext(),Preferences.class);
			startActivity(settingsActivity);
		}
	};
	
	private OnClickListener connectionListenerRobot = new OnClickListener() {
		
		public void onClick(View v) {

			boolean result;
			
			if(RobotConnection.Connected == false){
				
				//connect
				result = RobotConnection.Connect();
				
				//connection failed
				AlertDialog.Builder builder = new AlertDialog.Builder(ABRC.this);
				builder.setCancelable(true);
				if(result == false){
					builder.setTitle("Connection info");
					builder.setMessage("Could not connect to the robot at " + RobotConnection.Hostname + ":" + RobotConnection.Port);
					builder.setIcon(R.drawable.icon_error);
				}else{
					//successfully connected, update button
					redraw_buttons_and_colors();
					builder.setTitle("Connection info");
					builder.setMessage("Successfully connected to the robot.");
					builder.setIcon(R.drawable.icon_good);
				}
				builder.setNegativeButton("OK", null);
				AlertDialog dlg = builder.create();
				dlg.show();
				
			}else{
				//disconnect
				RobotConnection.Disconnect();
				
				//successfully disconnected update button
				redraw_buttons_and_colors();
			}
		}
	};
	
	private OnClickListener connectionListenerCameras = new OnClickListener() {
		
		public void onClick(View v) {
			
			int result;
			
			if(MjpegView.NumConnected != MjpegView.NumCameras){
				//connect
				
				result = MjpegView.ConnectAll();
				
				AlertDialog.Builder builder = new AlertDialog.Builder(ABRC.this);
				builder.setCancelable(true);
				if(result < MjpegView.NumCameras){
					
					builder.setTitle("Connection info");
					builder.setMessage("Connected to " + MjpegView.NumConnected + " of " + MjpegView.NumCameras + " cameras");
					if(MjpegView.NumConnected != 0){
						builder.setIcon(R.drawable.icon_warning);
					}else{
						builder.setIcon(R.drawable.icon_error);
					}
					
				}else{
					builder.setTitle("Connection info");
					builder.setMessage("Successfully connected to all cameras");
					builder.setIcon(R.drawable.icon_good);
				}
				builder.setNegativeButton("OK", null);
				AlertDialog dlg = builder.create();
				dlg.show();
				
			}else{
				//disconnect
				MjpegView.DisconnectAll();
			}
			
			//update gui to match our connection state
			redraw_buttons_and_colors();
			
		}
	};
	
	private void getPrefs() {
		String str_robot_port;
		int i;
		
        // Get the xml/preferences.xml preferences
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        RobotConnection.Hostname = prefs.getString("pref_robot_hostname","");
        str_robot_port = prefs.getString("pref_robot_port","");
        
        //get camera preferences
        for(i=0;i<MjpegView.NumCameras;i++){
            MjpegView.Hostnames[i] = prefs.getString("pref_camera" + (i+1) + "_hostname","");
            MjpegView.Usernames[i] = prefs.getString("pref_camera" + (i+1) + "_username","");
            MjpegView.Passwords[i] = prefs.getString("pref_camera" + (i+1) + "_password","");
            MjpegView.Types[i] = prefs.getString("pref_camera"+(i+1)+"_type","");
            
			MjpegView.HttpClients[i].getCredentialsProvider().setCredentials(
				new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
				new UsernamePasswordCredentials(MjpegView.Usernames[i],MjpegView.Passwords[i])
			); 
            
        }

        try{
        	RobotConnection.Port = Integer.valueOf(str_robot_port);
        }catch(NumberFormatException e){
        	RobotConnection.Port = 0;
        }
        
        Log.d("getPrefs","Host: " + RobotConnection.Hostname + " port: " + RobotConnection.Port);
	}
	
	/*
	This updates the main-menu display's elements that are dependent on our connection status.
	For example, it updates the button colors, labels, and border colors.
	We call this whenever our connection status changes or when we reload the main menu.
	*/
	private void redraw_buttons_and_colors(){
		
		View small_cam_bg;
		
		small_cam_bg = findViewById(R.id.small_cam_bg);
		
		//first setup buttons		
		if(RobotConnection.Connected == true){
			btn_connection_robot.setText("Disconnect Robot");
			btn_connection_robot.setBackgroundResource(R.drawable.red_button);
		}else{
			btn_connection_robot.setText("Connect Robot");
			btn_connection_robot.setBackgroundResource(R.drawable.green_button);
		}
		
		if(MjpegView.NumConnected == MjpegView.NumCameras){
			//all cameras connected
			btn_connection_cameras.setText("Disconnect Cameras");
			btn_connection_cameras.setBackgroundResource(R.drawable.red_button);
			small_cam_bg.setBackgroundResource(R.color.green_light);
		}else if(MjpegView.NumConnected > 0){
			//some connected
			btn_connection_cameras.setText("Connect Cameras");
			btn_connection_cameras.setBackgroundResource(R.drawable.yellow_button);
			small_cam_bg.setBackgroundResource(R.color.yellow_light);
		}else{
			//none connected
			btn_connection_cameras.setText("Connect Cameras");
			btn_connection_cameras.setBackgroundResource(R.drawable.green_button);
			small_cam_bg.setBackgroundResource(R.color.red_light);
		}
		
		//might only show one camera
		if(MjpegView.BigCamId != -1){
			MjpegView.MakeCamBig(MjpegView.BigCamId);
		}
		
	}
	
	@Override
	/*
	called after onCreate when we start the program,resume the program
	called first when we exit settings
	*/
	protected void onStart(){
		super.onStart();
		getPrefs();
	}
	
	@Override
	//called after onstart when we start the program, resume the program, or exit settings
	protected void onResume() {
		super.onResume();
		
		redraw_buttons_and_colors();
		
		MjpegView.UpdateMvProps();
	}

	@Override
	/*
	Gets called when the user goes to the settings screen or exits the app. 
	*/
	protected void onStop(){
		super.onStop();
		
	}

}
